<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <style>
        ul,li{
            margin:0;
            padding:0;
            list-style: none;
        }
        /*滚动条的样式*/
        ::-webkit-scrollbar {
            /*滚动条整体样式*/
            width: 4px;
            /*高宽分别对应横竖滚动条的尺寸*/
            height: 4px;
        }

        ::-webkit-scrollbar-thumb {
            /*滚动条里面小方块*/
            border-radius: 4px;
            box-shadow: inset 0 0 5px rgba(96, 97, 97, 0.2);
            background: #7a7878;
        }

        ::-webkit-scrollbar-track {
            /*滚动条里面轨道*/
            box-shadow: inset 0 0 5px rgba(96, 97, 97, 0.2);
            border-radius: 4px;
            background: #ededed;
        }

        h2 {
            width: 100%;
            border-bottom: 1px  solid #ccc;
            font-size:20px;
            margin: 0;
            height: 5%;
            line-height: 5vh;
        }
        .listItem{
            width: 100%;
            display:flex;
            align-items: start;
            margin:20px 0 ;
        }
        .img {
            width:50px;
            height:50px;
            line-height: 50px;
            text-align: center;
            background-color: #3a5498;
            border-radius: 50%;
            color: #fff;
            font-weight: bold;
            margin:0 10px;
        }
        .username {
            font-size:14px;
            font-weight: bold;
            color: #656565;
        }

        .msg {
            white-space: normal;
            overflow-wrap: break-word;
            max-width:70%;
            background-color: #fff;
            color: #000;
            padding: 10px;
            border-radius:4px;
        }
        .time {
            margin:0 10px;
            font-size:12px;
            color: #656565;
        }

        body {
            font-family: Arial, sans-serif;
            height: 100vh;
            overflow: hidden;
            background-color: #f2f2f2;
        }

        ul {
            height: 70%;
            box-sizing: border-box;
            overflow: auto;
        }

        .message-container {
            background-color: #f2f2f2;
            height:100%;
            border-top:1px solid #ccc;
            box-sizing: border-box;
            width: 100%;
            margin: 0 auto;
            padding:10px;
        }

        .message-input {
            width:100%;
            height:calc(100% - 60px);
            flex: 1;
            box-sizing: border-box;
            border:none;
            background:transparent;
            font-size: 16px;
            outline: none;
        }

        .send-button {
            float: right;
            padding: 10px 20px;
            border: none;
            background-color: #007bff;
            color: #fff;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 12px;
        }

        .send-button:hover {
            background-color: #0056b3;
        }
    </style>
    <body>
        <h2></h2>
        <ul id="list"></ul>
        <form style="height:25%;">
            <div class="message-container">
                <textarea class="message-input" rows="5" id="message" placeholder="请输入消息"></textarea>
                <button class="send-button" id="send">发送</button>
            </div>
        </form>

        <script>
            // js文件
            class Demo {
                constructor() {
                    // 确认是哪个用户的聊天室
                    document.querySelector("h2").innerHTML = `聊天室`;
                    this.list = document.querySelector("#list");
                    this.msg = document.querySelector("#message");
                    this.submit = document.querySelector("form");
                    // 本地连接，端口:9527
                    this.ws = new WebSocket("ws:192.168.101.118:9527");
                    // 存用户的名字，也就是谁发送的这条消息
                    this.username = "";


                    document.getElementById('message').addEventListener('keydown', function(e) {
                        if (e.key === 'Enter') {
                            // 阻止默认换行
                            e.preventDefault();
                            document.getElementById('send').click();
                        }
                    });

                    this.init();
                }
                init() {
                    this.bindEvent();
                }
                bindEvent() {
                    // 会有 this 指向问题，用 bind 绑一下
                    this.submit.addEventListener("submit", this.sendClick.bind(this));
                    this.ws.addEventListener("open", this.handleOpen.bind(this));
                    this.ws.addEventListener("close", this.handleClose.bind(this));
                    this.ws.addEventListener("error", this.handleError.bind(this));
                    this.ws.addEventListener("message", this.handleMessage.bind(this));
                }

                // 消息发送
                sendClick(e) {
                    // 阻止表单默认提交时刷新行为
                    e.preventDefault();
                    let msg = this.msg.value.trim();
                    // 如果为空什么都不做
                    if (msg.length === 0) {
                        return;
                    }

                    // 发送数据
                    this.ws.send(
                        JSON.stringify({
                            username: this.username,
                            userid: this.userid,
                            img: this.img,
                            dateTime: +new Date(),
                            msg,
                        })
                    );

                    this.msg.value = "";

                    this.refreshLocation();
                }

                handleOpen() {
                    // 是哪个用户发送的消息，需要知道
                    this.username = JSON.parse(localStorage.getItem("usernameInfo")).username;
                    this.userid = JSON.parse(localStorage.getItem("usernameInfo")).userid;
                    this.img = JSON.parse(localStorage.getItem("usernameInfo")).img;
                }

                handleClose() {
                    console.log("ws close");
                }

                handleError() {
                    console.log("ws error");
                }

                // 接收后端返回的数据
                handleMessage(e) {
                    const { username, userid,img,dateTime, msg } = JSON.parse(e.data);
                    // 把数据结合标签添加到页面上
                    let li = document.createElement("li");
                    if(this.userid === userid){
                        li.style.display = "flex";
                        li.style.justifyContent = "end";
                        li.innerHTML = `
                            <div class="listItem" style="justify-content: end">
                                <div style="max-width:80%">
                                    <div style="text-align: right;margin-bottom: 10px;"><span class="username">${username}</span></div>
                                    <div style="display: flex;justify-content: end;align-items: center;">
                                        <div class="time">${new Date(dateTime).toTimeString().split(' ')[0]}</div>
                                        <div class="msg" style="background-color: #0099ff;color:#fff">${msg}</div>
                                    </div>
                                </div>
                                <div class="img" style="background-color:${img}"><span>${username.slice(0,1)}</span></div>
                            </div>
                        `;
                    }else{
                        li.innerHTML = `
                            <div class="listItem">
                                <div class="img" style="background-color:${img}"><span>${username.slice(0,1)}</span></div>
                                <div style="max-width:80%">
                                    <div style="margin-bottom: 10px;"><span class="username">${username}</span></div>
                                    <div style="display: flex;justify-content: start;align-items: center;">
                                        <div class="msg">${msg}</div>
                                        <div class="time">${new Date(dateTime).toTimeString().split(' ')[0]}</div>
                                    </div>
                                </div>
                            </div>
                        `;
                    }
                    this.list.appendChild(li);

                    this.refreshLocation();
                }

                // 刷新聊天室位置
                refreshLocation() {
                    this.list.scroll({
                        top: 100000000000000,
                        left: 0,
                        behavior: "smooth",
                    });
                }
            }

            new Demo();
        </script>
    </body>
</html>
